The insert operation is a two-step process to add an element while preserving the heap's integrity.
- Step 1 (Maintain Shape): Add the new element to the first available spot at the bottom of the tree. In the array representation, this simply means appending it to the end. This always maintains the complete tree property.
- Step 2 (Restore Heap Property): The new element's value might violate the heap property (e.g., be larger than its parent in a max-heap). We fix this by "bubbling up" the new element into its correct position.
Key Idea
First, satisfy the shape property. Then, fix the heap property.
Array Representation